package com.mf.verify;


import com.mf.exception.CustomExceptionHandler;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: lmf
 * @Create: 2024/4/14 7:35
 * Description:  验证字段
 */
public class verifyField {
    public static void isEmpty(Object instance, List<String> fieldNames)  {
        Class<?> clazz = instance.getClass();
        ArrayList<String> emptyFieldNames = new ArrayList<>();

        for (String fieldName : fieldNames) {
            try {
                // 获取字段的 Field 对象
                Field field = clazz.getDeclaredField(fieldName);

                // 设置字段为可访问（如果需要）
                field.setAccessible(true);

                // 获取字段的值
                Object value = field.get(instance);

                // 检查字段值是否为 null 或空字符串（仅对 String 类型字段）
                if (value == null || (value instanceof String && ((String) value).isEmpty())) {
                    emptyFieldNames.add(fieldName);
                }
            } catch (NoSuchFieldException | IllegalAccessException e) {
                // 处理反射相关的异常
                throw new RuntimeException("Error checking field value for field '" + fieldName + "'", e);
            }
        }


        if (!emptyFieldNames.isEmpty()) {
            throw new CustomExceptionHandler("字段 " + String.join(", ", emptyFieldNames) + " 不能为空");
        }
    }


    // 获取对象的字段值
    public static Object getFieldValue(Object obj, String fieldName) throws NoSuchFieldException, IllegalAccessException {
        Field field = obj.getClass().getDeclaredField(fieldName);
        field.setAccessible(true);
        return field.get(obj);
    }


}
